package com.hmall.searchService.controller;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.searchService.pojo.ItemDoc;
import com.hmall.searchService.pojo.RequestParams;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class ItemSearchController {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;

    /**
     * 根据搜索条件进行过滤
     * @param params
     * @return
     */
    @PostMapping("/filters")
    public Map<String, List<String>> filtersForItem(@RequestBody RequestParams params) {
        try {
            // 准备Request
            SearchRequest request = new SearchRequest("gouwu");
            //2 dsl
            // 2.1query
            buildBaseQuery(params, request);
            // 2.2size
            request.source().size(0);
            // 2.3聚合
            buildAggregation(request);
            // 3 发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4 解析结果
            Map<String,List<String>> map = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1 解析品牌
           List<String> brandList =  getAggByName(aggregations,"brandAgg");
            map.put("brand",brandList);
            // 4.2 解析分类
            List<String> categoryList =  getAggByName(aggregations,"categoryAgg");
            map.put("category",categoryList);

            return map;
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }
    }



    /**
     * 自动填充
     *
     * @param key
     * @return
     */
    @GetMapping("/suggestion")
    public List<String> ItemSuggestion(@RequestParam("key") String key) {
        try {
            SearchRequest request = new SearchRequest("gouwu");
            //dsl
            request.source().suggest(
                    new SuggestBuilder().addSuggestion(
                            "suggestions",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)
                                    .size(10)
                    )
            );
            // 发请求
            SearchResponse response  = client.search(request, RequestOptions.DEFAULT);


            //解析请求
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();

            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 条件过滤和查询
     * @param params
     * @return
     */
    @PostMapping("/list")
    public PageDTO<ItemDoc> searchByList(@RequestBody RequestParams params) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("gouwu");
            //准备DSL
            buildBaseQuery(params, request);
            //分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //高亮
            request.source().highlighter(
                    new HighlightBuilder().field("name").requireFieldMatch(false)
            );


            //解析相应

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 解析相应结果
     *
     * @param response
     * @return
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //解析响应
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        //文档数组
        SearchHit[] hits = searchHits.getHits();
        //遍历封装
        List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);

            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                //根据字段获取高亮结果
                HighlightField name = highlightFields.get("name");
                if (name != null){
                    // 获取高亮值
                    String string = name.getFragments()[0].string();
                    //覆盖非高亮结果
                    itemDoc.setName(string);
                }
            }
            itemDocs.add(itemDoc);
        }
        PageDTO<ItemDoc> pageDTO = new PageDTO<>();
        pageDTO.setList(itemDocs);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    /**
     * 条件拆查询
     *
     * @param params
     * @param request
     */
    private void  buildBaseQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // query
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 分类
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 品牌
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice()*100)
                    .lte(params.getMaxPrice()*100));
        }
        //排序
        if ("price".equals(params.getSortBy())){
            request.source().sort("price", SortOrder.DESC);
        }else if ("sold".equals(params.getSortBy())){
            request.source().sort("sold", SortOrder.DESC);
        }

        request.source().query(boolQuery);
    }

    /**
     * 聚合
     *
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        ) ;
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        ) ;

    }

    /**
     * 获取聚合集合
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 根据名称获取聚合结果
        Terms aggTerms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = aggTerms.getBuckets();
        // 遍历
        List<String> aggList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            aggList.add(keyAsString);
        }
        return aggList;
    }

}
